package com.tanhua.admin.module.usermanager.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.admin.module.usermanager.mapper.UserActiveMapper;
import com.tanhua.admin.module.usermanager.mapper.UserFreezeMapper;
import com.tanhua.admin.module.usermanager.pojo.UserActive;
import com.tanhua.admin.module.usermanager.pojo.UserFreeze;
import com.tanhua.admin.module.usermanager.pojo.UserLike;
import com.tanhua.admin.module.usermanager.service.UserManagerService;
import com.tanhua.admin.module.usermanager.vo.PageResult;
import com.tanhua.admin.module.usermanager.vo.UserInfoVo;
import com.tanhua.admin.module.usermanager.vo.UserManagerPageInfoVo;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RocketMQMessageListener(
        topic = "tanhua-sso-login",
        consumerGroup = "tanhua-admin",
        selectorExpression = "*")
public class UserManagerServiceImpl implements UserManagerService, RocketMQListener<String> {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFreezeMapper userFreezeMapper;

    @Autowired
    private UserActiveMapper userActiveMapper;

    @Override
    public PageResult getUserStatus(Map<String, String> map) {
        //解析参数
        Integer pagesize = Integer.valueOf(map.get("pagesize"));
        Integer page = Integer.valueOf(map.get("page"));
        String id = map.get("id");
        String nickname = map.get("nickname");
        String city = map.get("city");
        //分页设置
        IPage<UserInfo> iPage = new Page<>(page, pagesize);
        //查询参数设置
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(id)) {
            Long userId = Long.valueOf(id);
            queryWrapper.eq("user_id", userId);
        }
        if (ObjectUtil.isNotEmpty(nickname)) {
            queryWrapper.like("nick_name", nickname);
        }
        if (ObjectUtil.isNotEmpty(city)) {
            queryWrapper.like("city", city);
        }
        //查询userInfo表
        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(iPage, queryWrapper);
        PageResult pageResult = new PageResult();
        //如果查询结果为空,返回默认数据
        if (CollUtil.isEmpty(userInfoIPage.getRecords())) {
            pageResult.setPages(0);
            pageResult.setCounts(0);
            pageResult.setPage(page);
            pageResult.setPagesize(pagesize);
            pageResult.setItems(new ArrayList<>());
            return pageResult;
        }
        List<UserInfo> userInfoList = userInfoIPage.getRecords();
        //获取用户id集合
        List<Object> userIdList = CollUtil.getFieldValues(userInfoList, "userId");
        //查询user表
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("id", userIdList);
        List<User> users = userMapper.selectList(wrapper);
        //根据id查询userFreeze
        QueryWrapper<UserFreeze> freezeWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        List<UserFreeze> userFreezeList = userFreezeMapper.selectList(freezeWrapper);
        //查询user_active表
        QueryWrapper<UserActive> activeQuery = new QueryWrapper<>();
        activeQuery.in("user_id", userIdList);
        List<UserActive> userActiveList = userActiveMapper.selectList(activeQuery);
        //封装视图对象
        pageResult.setPages((int) userInfoIPage.getPages());
        pageResult.setCounts((int) userInfoIPage.getTotal());
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

        List<UserManagerPageInfoVo> listVo = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserManagerPageInfoVo userManagerPageInfoVo = new UserManagerPageInfoVo();
            userManagerPageInfoVo.setId(userInfo.getUserId().intValue());
            userManagerPageInfoVo.setAge(userInfo.getAge());
            userManagerPageInfoVo.setNickname(userInfo.getNickName());
            userManagerPageInfoVo.setLogo(userInfo.getLogo());
            userManagerPageInfoVo.setSex(userInfo.getSex().toString());
            userManagerPageInfoVo.setUserStatus("1");
            if (CollUtil.isNotEmpty(userFreezeList)){
                for (UserFreeze userFreeze : userFreezeList) {
                    if (userFreeze.getUserId() == userInfo.getUserId())
                    userManagerPageInfoVo.setUserStatus("2");
                }
            }
            userManagerPageInfoVo.setLogoStatus("1");
            userManagerPageInfoVo.setOccupation(userInfo.getIndustry());
            userManagerPageInfoVo.setCity(userInfo.getCity());
            for (User user : users) {
                if (user.getId() == userInfo.getUserId()) {
                    userManagerPageInfoVo.setMobile(user.getMobile());
                    break;
                }
            }
            userManagerPageInfoVo.setLastActiveTime(null);
            for (UserActive userActive : userActiveList) {
                if (userActive.getUserId() == userInfo.getUserId()){
                    userManagerPageInfoVo.setLastActiveTime(userActive.getActiveDate());
                    break;
                }
            }
            listVo.add(userManagerPageInfoVo);
        }

        pageResult.setItems(listVo);
        return pageResult;
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        //验证参数
        if (ObjectUtil.isEmpty(userId)) {
            return null;
        }
        //根据id查询user表
        User user = userMapper.selectById(userId);
        //根据id查询userInfo表
        QueryWrapper<UserInfo> userInfoQuery = new QueryWrapper<>();
        userInfoQuery.eq("user_id",userId);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQuery);
        //根据id查询user_active表
        QueryWrapper<UserActive> activeQuery = new QueryWrapper<>();
        activeQuery.eq("user_id",userId);
        UserActive userActive = userActiveMapper.selectOne(activeQuery);
        //根据id查询userFreeze
        QueryWrapper<UserFreeze> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserFreeze userFreeze = userFreezeMapper.selectOne(queryWrapper);
        String userStatus = "1";
        if (ObjectUtil.isNotEmpty(userFreeze)) {
            userStatus = "2";
        }
        //根据id查询user_like表中喜欢的人数
        Query query1 = new Query(Criteria.where("userId").is(userId));
        List<UserLike> likeList = mongoTemplate.find(query1, UserLike.class);
        Integer likeCount = likeList.size();
        //根据id查询被喜欢的人数
        Query query2 = new Query(Criteria.where("likeUserId").is(userId));
        List<UserLike> beLikeList = mongoTemplate.find(query2, UserLike.class);
        Integer beLikeCount = beLikeList.size();
        //统计配对的数量(相互喜欢)
        Integer matchingCount = 0;
        for (UserLike likeUser : likeList) {
            for (UserLike BeLikeUser : beLikeList) {
                if (likeUser.getLikeUserId() == BeLikeUser.getUserId()) {
                    matchingCount++;
                }
            }
        }
        //封装视图对象
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(userId.intValue());
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setMobile(user.getMobile());
        userInfoVo.setSex(userInfo.getSex().toString());
        userInfoVo.setPersonalSignature(userInfo.getMarriage());
        userInfoVo.setAge(userInfo.getAge());
        userInfoVo.setCountBeLiked(beLikeCount);
        userInfoVo.setCountLiked(likeCount);
        userInfoVo.setCountMatching(matchingCount);
        String income = userInfo.getIncome();
        if (income.contains("万")){
            int index = income.indexOf("万");
            String substring = income.substring(0, index);
            if (substring.contains("-")){
                String[] split = substring.split("-");
                Integer num1 = Integer.valueOf(split[0]);
                Integer num2 = Integer.valueOf(split[1]);
                userInfoVo.setIncome((num1 + num2) / 2);
            }else {
                userInfoVo.setIncome(Integer.valueOf(substring));
            }
        }else {
            userInfoVo.setIncome(Integer.valueOf(income));
        }
        userInfoVo.setOccupation(userInfo.getIndustry());
        userInfoVo.setUserStatus(userStatus);
        userInfoVo.setCreated(user.getCreated().getTime());
        userInfoVo.setCity(userInfo.getCity());
        if (ObjectUtil.isEmpty(userActive)){
            userInfoVo.setLastActiveTime(null);
        }else {
            userInfoVo.setLastActiveTime(userActive.getActiveDate());
        }
        //待优化
        userInfoVo.setLastLoginLocation(userInfo.getCity());
        userInfoVo.setLogo(userInfo.getLogo());
        userInfoVo.setTags(userInfo.getTags());

        return userInfoVo;
    }

    @Override
    public void onMessage(String msg) {
        Map map = JSON.parseObject(msg, HashMap.class);
        Long id = Long.valueOf(String.valueOf(map.get("id")));
        Long date = Long.valueOf(String.valueOf(map.get("date")));
        UserActive userActive = new UserActive();
        userActive.setUserId(id);
        userActive.setActiveDate(date);
        try {
            QueryWrapper<UserActive> query = new QueryWrapper<>();
            query.eq("user_id",id);
            UserActive active = userActiveMapper.selectOne(query);
            if (ObjectUtil.isEmpty(active)) {
                userActiveMapper.insert(userActive);
                return;
            }

            UpdateWrapper<UserActive> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id",userActive.getUserId());
            userActiveMapper.update(userActive, updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 用户冻结操作
     * @param userFreeze
     * @return
     */
    @Override
    public Integer getUserFreeze(UserFreeze userFreeze) {
        return userFreezeMapper.insert(userFreeze);
    }


    /**
     * 用户解冻操作
     */
    @Override
    public Integer getUserUnFreeze(Map<String,Object> map) {

        if(null == map){
            return null;
        }

        Object userId = map.get("userId");
        Long.valueOf(String.valueOf(userId));

        QueryWrapper<UserFreeze> wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        return userFreezeMapper.delete(wrapper);
    }
}
